package com.ihighest.app.infox.activity;

import io.rong.imkit.RongIM;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.api.ApiCallback;
import com.ihighest.app.common.api.ApiParam;
import com.ihighest.app.common.api.ApiResult;
import com.ihighest.app.common.kit.AppKit;
import com.ihighest.app.common.kit.SharedPreferencesKit;
import com.ihighest.app.common.kit.ToastKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.adapter.ImageListviewAdapter;
import com.ihighest.app.infox.adapter.QuestionContentListViewAdapter;
import com.ihighest.app.infox.myview.AKListView;
import com.ihighest.app.infox.myview.ActivityTitle;
import com.ihighest.app.infox.myview.HorizontialListView;
import com.ihighest.app.infox.tools.InitShare;
import com.umeng.socialize.bean.SHARE_MEDIA;

public class QuestionContentActivity extends BaseActivity implements OnClickListener {
	private static final String TAG = "QuestionContentActivity";
	private ActivityTitle title;
	JSONArray images;
	AKListView answerList;
	QuestionContentListViewAdapter questionAdapter;
	private JSONArray jsonArray;
	private String qid = "";// 问题id
	private String name = "", image, content, state, area, tag, rid, voice, uid;
	private String plantname, gold, weather, measure;
	private TextView plantnameTextView, goldTextView, weatherTextView, measureTextView;
	private int answers;
	private long time;
	private Boolean fav = false;
	private Boolean isAnswer = false;
	private ImageView iconimage;
	private ImageView voiceimage;
	private ImageListviewAdapter imageListviewAdapter;

	private TextView nametTextView, addresTextView, timeTextView, tagTextView, contentTextView, stateTextView, answerTextView;
	private Button myAnswer;
	private HorizontialListView imagesListView;
	private ArrayList<String> imagelist;

	private PopupWindow mPopupWindow;

	private SHARE_MEDIA shareTo;

	private InitShare share;
	private final String fileFolder = Environment.getExternalStorageDirectory().getPath() + "/infox/";
	File viocefile;
	String path = "";
	private String url;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.infox_activity_questioncomtent);
		title = (ActivityTitle) findViewById(R.id.questionContentTitle);
		title.setViewVersible(title.rightLayout, title.titleBack);
		title.setViewGone(title.titleMsg, title.titleSetting, title.titleRefresh);
		imagelist = new ArrayList<String>();
		qid = getIntent().getStringExtra("id");
		getquestiondata();
		// imagelist = AgriculturalTechnologyActivity.imagelist;

		jsonArray = new JSONArray();
		answerList = (AKListView) findViewById(R.id.answerList);

		iconimage = (ImageView) findViewById(R.id.questionContentUserImg);
		nametTextView = (TextView) findViewById(R.id.questionContentUserName);
		addresTextView = (TextView) findViewById(R.id.questionContentUserAddress);
		timeTextView = (TextView) findViewById(R.id.questionContentDate);
		tagTextView = (TextView) findViewById(R.id.questionContentAttribute);
		contentTextView = (TextView) findViewById(R.id.questionContentQuestion);
		stateTextView = (TextView) findViewById(R.id.questionSolve);
		answerTextView = (TextView) findViewById(R.id.questionAnswerCount);
		imagesListView = (HorizontialListView) findViewById(R.id.questionContentImglist);
		myAnswer = (Button) findViewById(R.id.myAnswer);
		voiceimage = (ImageView) findViewById(R.id.id_voice);
		plantnameTextView = (TextView) findViewById(R.id.id_plantname);
		weatherTextView = (TextView) findViewById(R.id.id_weather);
		measureTextView = (TextView) findViewById(R.id.id_measure);
		goldTextView = (TextView) findViewById(R.id.id_gold);

		share = new InitShare(this);
		iconimage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(QuestionContentActivity.this, UserDetailActivity.class);
				intent.putExtra("userId", uid);
				startActivity(intent);

			}
		});

		answerList.setOnItemClickListener(new OnItemClickListener() {
			Intent intent = null;

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

				if (TextUtils.isEmpty(SharedPreferencesKit.getString(QuestionContentActivity.this, Const.SP_KEY_USER_ID))) {
					intent = new Intent(QuestionContentActivity.this, LoginActivity.class);
					ToastKit.showShort(QuestionContentActivity.this, Const.UN_LOGIN_ALERT);
					startActivity(intent);
					return;
				} else if (SharedPreferencesKit.getString(QuestionContentActivity.this, Const.SP_KEY_USER_ID, "").equalsIgnoreCase(uid)) {
					// 打开与回答人聊天界面

					try {
						Const.IM_EXTRA = "chat_issue_ask:" + qid + ":"
								+ jsonArray.getJSONObject(arg2).getJSONObject("answer").getString("mid") + ":"
								+ SharedPreferencesKit.getString(QuestionContentActivity.this, Const.SP_KEY_USER_MID);
						RongIM.getInstance().startPrivateChat(QuestionContentActivity.this,
								jsonArray.getJSONObject(arg2).getJSONObject("answer").getString("rid"), "[" + name + "]" + "的提问");
						return;
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} else
					try {
						if (SharedPreferencesKit.getString(QuestionContentActivity.this, Const.SP_KEY_USER_ID, "").equalsIgnoreCase(
								jsonArray.getJSONObject(arg2).getJSONObject("answer").getString("uid"))) {

							Const.IM_EXTRA = "chat_issue_reply:" + qid + ":"
									+ SharedPreferencesKit.getString(getApplicationContext(), Const.SP_KEY_USER_MID) + ":"
									+ SharedPreferencesKit.getString(getApplicationContext(), Const.SP_KEY_USER_MID);

							RongIM.getInstance().startPrivateChat(QuestionContentActivity.this, rid, "[" + name + "]" + "的提问");
							return;
						}
					} catch (JSONException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}

				intent = new Intent(QuestionContentActivity.this, AnswerDetailActivity.class);
				intent.putExtra("qid", qid);
				try {
					intent.putExtra("tmid", jsonArray.getJSONObject(arg2).getJSONObject("answer").getString("mid"));

				} catch (JSONException e) {
					e.printStackTrace();
				}

				startActivity(intent);

			}
		});
	}

	/**
	 * 获取问题详情
	 * 
	 * 
	 * 
	 * @author yyh Created at 2015-11-2 下午4:03:41
	 */
	private void getquestiondata() {
		url = "http://info.nzdb.com.cn/app";
		if (!TextUtils.isEmpty(SharedPreferencesKit.getString(this, Const.SP_KEY_USER_ID))) {
			try {
				url = SharedPreferencesKit.getJsonObject(this, Const.SP_KEY_CONFIG_JSON).getString("downAppUrl") + "?code="
						+ SharedPreferencesKit.getString(this, Const.USER_InvitedCode) + "&mid="
						+ SharedPreferencesKit.getString(this, Const.SP_KEY_USER_MID);
			} catch (Exception e) {
				Log.e(TAG, e.getMessage(), e);
			}
	
		}
		Api.post("qa/issueDetail", ApiParam.create().addParam("id", qid), new ApiCallback(this) {

			@Override
			public void handleSuccess(ApiResult result) {
				try {
					if (result.getCode() == 100) {

						image = result.getData().getString("image");
						name = result.getData().getString("mname");
						area = result.getData().getString("area");
						time = result.getData().getLong("time");
						content = result.getData().getString("content");
						state = result.getData().getString("state");
						rid = result.getData().getString("rid");
						tag = result.getData().getString("tag");
						answers = result.getData().getInt("answers");
						fav = result.getData().getBoolean("fav");
						voice = result.getData().getString("voice");
						images = result.getData().getJSONArray("images");
						uid = result.getData().getString("uid");

						plantname = result.getData().getString("name");
						gold = result.getData().getString("gold");
						weather = result.getData().getString("weather");
						measure = result.getData().getString("measure");
						isAnswer = result.getData().getBoolean("meAnswer");
						for (int i = 0; i < images.length(); i++) {
							imagelist.add((String) images.get(i));
						}
					}
					init();
				} catch (JSONException e) {
					Log.e(TAG, e.getMessage(), e);
				}
			}

			@Override
			public void handleFailure(Exception e, String msg) {

				ToastKit.show(QuestionContentActivity.this, "加载失败", Toast.LENGTH_SHORT);

			}
		}, this);

	}

	@Override
	protected void onResume() {
		super.onResume();
		getdata();
	}

	/**
	 * 
	 * 获取回答列表
	 * 
	 * 
	 * @author yyh Created at 2015-10-27 下午12:02:22
	 */
	private void getdata() {
		if (qid != null) {

			Api.post("qa/answers", ApiParam.create().addParam("id", qid), new ApiCallback(QuestionContentActivity.this, true) {

				@Override
				public void handleSuccess(ApiResult result) {

					if (result.getDatas() == null || result.getDatas().length() <= 0) {

						// emptyview.setText("暂时还没有解决方案");
					}

					jsonArray = result.getDatas();
					questionAdapter = new QuestionContentListViewAdapter(QuestionContentActivity.this, jsonArray, qid, uid, name, rid);
					answerList.setAdapter(questionAdapter);

				}

				@Override
				public void handleFailure(Exception e, String msg) {

					// emptyview.setText("暂时还没有解决方案");

				}
			}, QuestionContentActivity.this);

		}
		if (!TextUtils.isEmpty(SharedPreferencesKit.getString(QuestionContentActivity.this, Const.SP_KEY_USER_ID))) {

			Api.get("share", ApiParam.create().addParam("dataId", qid).addParam("type", "QuestionsAnswers"), new ApiCallback(
					QuestionContentActivity.this) {
				private String shareId;

				@Override
				public void handleFailure(Exception e, String msg) {
				}

				@Override
				public void handleSuccess(ApiResult result) {
					try {
						shareId = result.getData().getString("ShareId");
					} catch (JSONException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					try {
						url = SharedPreferencesKit.getJsonObject(QuestionContentActivity.this, Const.SP_KEY_CONFIG_JSON).getString(
								"downAppUrl")
								+ "?code="
								+ SharedPreferencesKit.getString(QuestionContentActivity.this, Const.USER_InvitedCode)
								+ "&mid="
								+ SharedPreferencesKit.getString(QuestionContentActivity.this, Const.SP_KEY_USER_MID)
								+ "&ShareId="
								+ shareId;
					} catch (Exception e) {
						Log.e(TAG, e.getMessage(), e);
					}
				}
			}, QuestionContentActivity.this);
		}
	}

	private void init() {

		if (SharedPreferencesKit.getString(this, Const.SP_KEY_USER_ID, "").equalsIgnoreCase(uid)) {

			myAnswer.setVisibility(View.GONE);
		} else {
			myAnswer.setVisibility(View.VISIBLE);
		}

		if (isAnswer) {
			myAnswer.setText("继续回答");
		} else {
			myAnswer.setText("我来回答");
		}

		nametTextView.setText(name);
		if (name.length() > 5) {
			name = name.substring(0, 4) + "...";
		}

		title.setTitle("问题详情");

		// 分享

		title.setOtherImg(R.drawable.infox_title_share);

		title.titleOther.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				initSharePupoVindow();
				showPupop();
			}
		});
		// 收藏
		if (fav) {

			title.setSecondImg(R.drawable.infox_content_collection_perss);
		} else {
			title.setSecondImg(R.drawable.infox_person_get);

		}

		title.titleSearch.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (TextUtils.isEmpty(SharedPreferencesKit.getString(QuestionContentActivity.this, Const.SP_KEY_USER_ID))) {
					Intent intent = new Intent(QuestionContentActivity.this, LoginActivity.class);
					ToastKit.showShort(QuestionContentActivity.this, Const.UN_LOGIN_ALERT);
					startActivity(intent);
				} else {

					Api.post("me/favorite", ApiParam.create().addParam("id", qid).addParam("type", 4).addParam("action", fav ? 2 : 1),
							new ApiCallback(QuestionContentActivity.this, true) {

								@Override
								public void handleSuccess(ApiResult result) {
									if (fav) {
										title.setSecondImg(R.drawable.infox_person_get);
										fav = false;
									} else {
										title.setSecondImg(R.drawable.infox_content_collection_perss);
										fav = true;
									}
								}

								@Override
								public void handleFailure(Exception e, String msg) {
									ToastKit.showShort(mContext, "收藏失败");
								}
							}, QuestionContentActivity.this);

				}
			}
		});
		if (imagelist.size() == 0) {
			imagesListView.setVisibility(View.GONE);
		} else {
			imageListviewAdapter = new ImageListviewAdapter(this, imagelist);
			imagesListView.setVisibility(View.VISIBLE);
			imagesListView.setAdapter(imageListviewAdapter);
		}

		// DisplayImageOptions defaultOptions = new
		// DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.infox_person_no_icon)
		// .showImageOnFail(R.drawable.infox_person_no_icon).showImageOnLoading(R.drawable.infox_person_no_icon).cacheInMemory(true)
		// .cacheOnDisc(true).build();
		// ImageLoader.getInstance().displayImage(image, iconimage,
		// defaultOptions);
		AppKit.SetUserImg(image, iconimage);

		if (area.length() > 5) {
			area = area.substring(0, 5);
		}

		addresTextView.setText(area);
		contentTextView.setText(content);
		tagTextView.setText(tag);

		timeTextView.setText(AppKit.timeToBeforeStr(time));

		plantnameTextView.setText(plantnameTextView.getText() + plantname);

		if (weather == null || "".equals(weather)) {
			weatherTextView.setText(weatherTextView.getText() + "未填写");
		} else {
			weatherTextView.setText(weatherTextView.getText() + weather);
		}

		if (measure == null || "".equals(measure)) {
			measureTextView.setText(measureTextView.getText() + "未填写");
		} else {
			measureTextView.setText(measureTextView.getText() + measure);

		}
		if (gold == null || "".equals(gold)) {
			goldTextView.setText(goldTextView.getText());
		} else {

			goldTextView.setText(goldTextView.getText() + gold);

		}

		if (state == null || state.equals("0")) {
			stateTextView.setText("未解决");
			stateTextView.setBackgroundResource(R.drawable.infox_information_hotbg);
			stateTextView.setTextColor(this.getResources().getColor(R.color.not_resolve_color));

		} else {
			stateTextView.setText("已解决");
			stateTextView.setBackgroundResource(R.drawable.infox_information_dingyuebg);
			stateTextView.setTextColor(this.getResources().getColor(R.color.resolve_color));
			myAnswer.setVisibility(View.GONE);

		}
		answerTextView.setText(answers + "人回答");

		TextView emptyview = new TextView(this);
		emptyview.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		emptyview.setText("暂无回答");
		emptyview.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
		emptyview.setVisibility(View.GONE);
		answerList.setEmptyView(emptyview);
		// TODO 简单处理，打开聊天对话框
		myAnswer.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (TextUtils.isEmpty(SharedPreferencesKit.getString(QuestionContentActivity.this, Const.SP_KEY_USER_ID))) {
					startActivity(new Intent(QuestionContentActivity.this, LoginActivity.class));
				} else {
					if (isAnswer) {
						// 继续回答
						// chat_issue_reply:qid:aid:mid
						Const.IM_EXTRA = "chat_issue_reply:" + qid + ":"
								+ SharedPreferencesKit.getString(getApplicationContext(), Const.SP_KEY_USER_MID) + ":"
								+ SharedPreferencesKit.getString(getApplicationContext(), Const.SP_KEY_USER_MID);
					} else {
						Const.IM_EXTRA = "chat_issue:" + qid + ":"
								+ SharedPreferencesKit.getString(getApplicationContext(), Const.SP_KEY_USER_MID);
					}

					System.out.println(Const.IM_EXTRA);
					RongIM.getInstance().startPrivateChat(QuestionContentActivity.this, rid, "[" + name + "]" + "的提问");
				}
			}
		});
		System.out.println(voice);

		if (voice == null || voice.equals("")) {
			voiceimage.setVisibility(View.GONE);
		} else {
			voiceimage.setVisibility(View.VISIBLE);
			downloadVoice();

			voiceimage.setOnClickListener(new OnClickListener() {

				private MediaPlayer player;

				@Override
				public void onClick(View arg0) {

					if (path == null || path.equals("")) {
						return;

					}

					if (player == null) {

						player = new MediaPlayer();
						// player.setAudioStreamType(AudioManager.STREAM_ALARM);

					}
					try {
						player.reset();
						System.out.println(voice);
						player.setDataSource(viocefile.getPath());
						System.out.println(viocefile.getPath());
						System.out.println(path);
						player.prepare();
						player.start();

						// System.out.println(player.getDuration());

						player.setOnCompletionListener(new OnCompletionListener() {

							@Override
							public void onCompletion(MediaPlayer arg0) {
								Log.e("oncompletion", "voicestop");
								player.stop();
								player.release();
								player = null;
								voiceimage.setClickable(true);
							}
						});

					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (SecurityException e) {
						e.printStackTrace();
					} catch (IllegalStateException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}

				}
			});
		}

	}

	/**
	 * 
	 * 加载声音文件
	 * 
	 * 
	 * @author yyh Created at 2015-11-10 上午10:58:23
	 */
	private void downloadVoice() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				String newFilename = voice.substring(voice.lastIndexOf("/") + 1);

				File file = new File(fileFolder);
				if (!file.exists()) {
					file.mkdir();
				}
				path = newFilename = fileFolder + newFilename;
				viocefile = new File(path);
				// 如果目标文件已经存在，则删除。产生覆盖旧文件的效果
				if (viocefile.exists()) {
					viocefile.delete();
				}
				try {
					// 构造URL
					URL url = new URL(voice);
					// 打开连接
					URLConnection con = url.openConnection();

					con.connect();
					// 获得文件的长度
					int contentLength = con.getContentLength();
					System.out.println("长度 :" + contentLength);
					// 输入流
					InputStream is = con.getInputStream();
					// 1K的数据缓冲
					byte[] bs = new byte[1024];
					// 读取到的数据长度
					int len;
					// 输出的文件流
					OutputStream os = new FileOutputStream(viocefile);
					// 开始读取
					while ((len = is.read(bs)) != -1) {
						os.write(bs, 0, len);
					}
					// 完毕，关闭所有链接
					os.close();
					is.close();

				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}).start();

	}

	@Override
	protected void onPause() {
		super.onPause();

	}

	@SuppressLint("InflateParams")
	@SuppressWarnings("deprecation")
	private void initSharePupoVindow() {

		LayoutInflater layoutInflater = LayoutInflater.from(this);
		View popupWindow = layoutInflater.inflate(R.layout.infox_activity_content_share_popu, null);

		mPopupWindow = new PopupWindow(popupWindow, android.view.ViewGroup.LayoutParams.MATCH_PARENT,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
		// 必须设置背景
		mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		// 设置点击其他地方 就消失 (只设置这个，没有效果)

		mPopupWindow.setOutsideTouchable(true); /* 设置触摸外面时消失 */
		popupWindow.findViewById(R.id.shareToWeixin).setOnClickListener(this);
		popupWindow.findViewById(R.id.shareToFriendCircle).setOnClickListener(this);
		popupWindow.findViewById(R.id.shareToMessage).setOnClickListener(this);
		popupWindow.findViewById(R.id.shareToQQ).setOnClickListener(this);
		popupWindow.findViewById(R.id.shareToWeb).setOnClickListener(this);
		popupWindow.findViewById(R.id.shareEmail).setOnClickListener(this);
		popupWindow.findViewById(R.id.transpond).setOnClickListener(this);
		popupWindow.findViewById(R.id.shareCopyLink).setOnClickListener(this);
		popupWindow.findViewById(R.id.cancle).setOnClickListener(this);

	}

	@Override
	public void onClick(View view) {
		

		switch (view.getId()) {
		case R.id.shareToWeixin:
			shareTo = SHARE_MEDIA.WEIXIN;
			share.setMyShareContent(content, url);
			share.isShareSuccess(shareTo);
			break;
		case R.id.shareToFriendCircle:
			shareTo = SHARE_MEDIA.WEIXIN_CIRCLE;
			share.setMyShareContent(content, url);
			share.isShareSuccess(shareTo);
			break;
		case R.id.shareToMessage:
			shareTo = SHARE_MEDIA.SMS;
			share.setMyShareContent(content, url);
			share.isShareSuccess(shareTo);
			break;
		case R.id.shareToQQ:
			shareTo = SHARE_MEDIA.QQ;
			share.setMyShareContent(content, url);
			share.isShareSuccess(shareTo);
			break;
		case R.id.shareToWeb:
			shareTo = SHARE_MEDIA.SINA;
			share.setMyShareContent(content, url);
			share.isShareSuccess(shareTo);
			break;
		case R.id.shareEmail:
			shareTo = SHARE_MEDIA.EMAIL;
			share.setMyShareContent(content, url);
			share.isShareSuccess(shareTo);
			break;
		case R.id.transpond:

			ToastKit.showShort(getApplicationContext(), Const.UN_FINISH_ALERT);
			break;
		case R.id.shareCopyLink:

			ClipboardManager clip = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
			if (Build.VERSION.SDK_INT >= 11) {
				ClipData clipData = ClipData.newPlainText("App下载链接", url);
				clip.setPrimaryClip(clipData);
			} else {
				clip.setText(url);
			}
			break;
		case R.id.cancle:
			mPopupWindow.dismiss();
			break;

		}
	}

	private void showPupop() {

		if (mPopupWindow.isShowing()) {
			mPopupWindow.dismiss();
		} else {
			mPopupWindow.showAtLocation(findViewById(R.id.id_parent), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
		}

	}

}
